package com.liip.jt808.util;

/**
 * CRC8 is based on the polynomial = X^8 + X^5 + X^4 + 1
 * @author LuoLin
 * @Date:	2020/08/19
 */
public class CRC8Util {
	/**
     * 	计算CRC8校验值
     *
     * @param buffer   数据
     * @return 校验值
     */
	public static int CRC8_i(byte[] buffer){
		int crci=0xFF;   //起始字节FF
        for (int j = 0; j < buffer.length; j++)
        {
            crci ^= buffer[j] & 0xFF;   
            for (int i = 0; i < 8; i++)
            {
                if ((crci & 1) != 0)
                {
                    crci >>= 1;
                    crci ^= 0xB8;    //多项式当中的那个啥的，不同多项式不一样
                }
                else
                {
                    crci >>= 1;
                }
            }
        }
        return crci;
	}
	
	/**
     * 	计算CRC8校验值
     *
     * @param buffer   数据
     * @return 校验值
     */
	public static byte CRC8(byte[] buffer){
        return (byte)CRC8_i(buffer);
    }
}
